//
//  CLComposeView.swift
//  CLWeibo
//
//  Created by 陈亮 on 16/7/16.
//  Copyright © 2016年 陈亮. All rights reserved.
//

import UIKit
import pop

class CLComposeView: UIView {

    //记录在哪个控制器上弹出
    private var target:UIViewController?
    //定义执行动画的数组
    private lazy var composeButtonArray = [CLComposeMenuButton]()
    // MARK:  懒加载控件
    private lazy var bgImageView:UIImageView = UIImageView(image: UIImage.getScreenShot().applyLightEffect())
    
    //构造函数重载
    override init(frame: CGRect) {
        super.init(frame:frame)
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //设置界面
    private func setUpUI (){
    
        self.frame.size = CGSize(width: ScreenWidth, height: ScreenHeight)
        //添加控件
        addSubview(bgImageView)
        //设置约束
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self).offset(UIEdgeInsetsZero)
        }
        loadComposePlist()
        addChildButton()
    }

    
    
    // MARK:  读取plist文件
    private func loadComposePlist() -> [CLComposeMenu]{
        
        //获取路径
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)
        //读取plist
        let composeArray = NSArray(contentsOfFile: path!)
        
        //定义临时空的数组
        var tempArray = [CLComposeMenu]()
        //遍历  字典转模型
        for dic in composeArray! {
            let compose = CLComposeMenu(dic: dic as! [String:AnyObject])
            tempArray.append(compose)
        }
        return tempArray
        
    }
    
    //添加6个子控件
    private func addChildButton() {
        //按钮的宽度
        let buttonWidth:CGFloat = 80
        //按钮的高度
        let buttonHeight:CGFloat = 110
        //间距
        let itemMargin:CGFloat = (width - 3 * buttonWidth) / 4
        //获取plist文件里面的数据
        let composeArray = loadComposePlist()
        
        for(i,value) in composeArray .enumerate(){
            let button = CLComposeMenuButton()
            //设置模型
            button.composeMenu = value
            //按钮的点击事件
            button.addTarget(self, action: "buttonClickAction:", forControlEvents: .TouchUpInside)
            button.size = CGSize(width: buttonWidth, height: buttonHeight)
            //计算列的索引
            let cols = i % 3
            //行的索引
            let rows = i / 3
            
            //计算x坐标
            button.x = buttonWidth * CGFloat(cols) + CGFloat(cols + 1) * itemMargin
            button.y = buttonHeight * CGFloat(rows) + CGFloat(rows) * itemMargin + ScreenHeight
            button.setImage(UIImage(named: value.icon!), forState: .Normal)
            button.setTitle(value.title!, forState: .Normal)
            //添加到
            addSubview(button)
            composeButtonArray.append(button)
            
        }
        
    }
    //按钮点击事件
    @objc private func buttonClickAction(btn:CLComposeMenuButton){
     
        //点击的时候 产生一个变大变小的动画
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            for value in self.composeButtonArray {
                //被点击的按钮透明度
                value.alpha = 0.2
                if value == btn {
                    //被点击的按钮放大  其他按钮变小
                    value.transform = CGAffineTransformMakeScale(2, 2)
                }else {
                    //缩小
                    value.transform = CGAffineTransformMakeScale(0.3, 0.3)
                }
            }
            }) { (_) -> Void in
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    for value in self.composeButtonArray {
                        value.alpha = 1
                        value.transform = CGAffineTransformIdentity
                    }
                    }, completion: { (_) -> Void in
                        //跳转控制器
                        let classType = NSClassFromString(btn.composeMenu!.className!) as! UIViewController.Type
                        //创建指定对象
                        let vc = classType.init()
                        //创建导航控制器
                        let nav = UINavigationController(rootViewController: vc)
                        self.target?.presentViewController(nav, animated: true, completion: { () -> Void in
                            self.removeFromSuperview()
                        })
                })
        }
        
    }
    //显示pop动画
    func show(target:UIViewController){
        
        self.target = target
        //获取最上面的一个window
        target.view.addSubview(self)
        //开启动画
        for (i,value) in composeButtonArray.enumerate() {
            startAnimation(value, i: i, isUp: true)
        }
        
    }
    //开启动画
    private func startAnimation(value: UIButton, i: Int, isUp: Bool) {
        //  改变视图中心点的弹簧动画
        let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        
        let y = isUp ? value.centerY - 350 : value.centerY + 350
        
        //  动画目的地
        animation.toValue = NSValue(CGPoint: CGPoint(x: value.centerX, y: y))
        //  弹簧弹力
        animation.springBounciness = 8
        //  弹簧速度
        animation.springSpeed = 10
        //  一个一个弹出
        animation.beginTime = CACurrentMediaTime() + Double(i) * 0.025
        //  执行动画
        value.pop_addAnimation(animation, forKey: nil)
    }
    
    //点击回到主界面
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        //开启向下的动画
        for (i,value) in (composeButtonArray.reverse().enumerate()) {
            startAnimation(value, i: i, isUp: false)
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.3 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
            //  结束刷新
            self.removeFromSuperview()
        })
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
}
